<?php
namespace control;
/*
*奖惩记录类
*/

class rewardsClass extends adIndexClass
{
    private const page = 'rewards';
    private const table = 'rewards';
    private const title = '奖惩记录';
    public array $stateOption = ['草稿', '审核中', '已通过'];


    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => '登记日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'staff' => [
                        'name'  => "员工姓名",
                        'width' => 100,
                    ],
                    'tel'  => [
                        'name'  => "联系电话",
                        'width' => 100,
                    ],
                    'department'         => [
                        'name'  => '部门',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'level'          => [
                        'name'  => '奖惩级别',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type'          => [
                        'name'  => '奖惩类型',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'money'          => [
                        'name'  => '奖惩金额',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'reason'          => [
                        'name'  => '奖惩事由',
                        'width' => 200,
                    ],
                    'method'          => [
                        'name'  => '奖惩方式',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'deptName'          => [
                        'name'  => '签发部门',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'stid'          => [
                        'name'  => '签发人',
                        'width' => 100
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function rewardsRecordOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    '奖惩类型' => select(["name" => "type", 'option' => explode('，', para('rewardsType'))]).
                        hidden(array("name" => "targetId", "value" => $this->get('id'))),
                    '奖惩级别'   => select(["name" => "level", 'option' => explode('，', para('rewardsLevel'))]),
                    "奖惩事由"   => text(array("name" => "reason")),
                ],
                [
                    "登记日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 员工页卡奖惩记录
     *
     * @return bool|string
     */
    public function rewardsRecord(): bool|string
    {
        $html = $this->rewardsRecordOptions(false);
        $button = "";
        //返回
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function rewardsRecordSearch(): bool|string
    {
        $id = $this->post('targetId');
        $and = " and staffId = '$id'";
        //like查询数组
        $like = array(
            "reason" => $this->post('reason'),
        );
        //全等查询数组
        $equal = array(
            "state" => '已通过',
            "level" => $this->post('level'),
            "type" => $this->post('type'),
        );
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            $staff  =query('staff',"stid = '$array[staffId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "staff":
                        $row[] = $staff['name'];
                        break;
                    case "tel":
                        $row[] = $staff['tel'];
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'money'      => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='trainRecordForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $where = !$this->power(self::page, 'seeAll')?" and stid = '" . self::$stid . "' ":'';
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "员工" => selectMultiple(array('table' => 'staff', 'where' => " 1=1 {$where} ", 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'staffId', 'class' => 'width200')),
                    "联系电话"   => text(array("name" => "contactTel")),
                    "部门"   => text(array("name" => "department")),
                ],
                [
                    '奖惩类型'  => select(["name" => "type", 'option' => explode('，', para('rewardsType'))]),
                    "奖惩级别" => select(["name" => "level", 'option' => explode('，', para('rewardsLevel'))]),
                    '奖惩事由' => text(array("name" => "reason")),
                ],
                [
                    "登记日期" => text(array("name" => "createTime",'laydate'=>['range'=>'~'])),
                    "状态" => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "reason" => $this->post('reason'),
            "department" => $this->post('department'),
        );
        //全等查询数组
        $equal = array(
            "staffId" => $this->post('staffId'),
            "state" => $this->post('state'),
            "level" => $this->post('level'),
            "type" => $this->post('type'),
        );
        $and = "";
        if ($this->post('contactTel')){
            $and.=" and staffId in (select stid from staff where tel like '%".$this->post('contactTel')."%')";
        }
        if (!$this->power(self::page, 'seeAll')) {
            $and .= " and staffId = '" . self::$stid . "' ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => $array['state'] !='草稿'?[]:array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            $staff  =query('staff',"stid = '$array[staffId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "staff":
                        $row[] = $staff['name'];
                        break;
                    case "tel":
                        $row[] = $staff['tel'];
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'money'      => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "登记日期：" => text(["name" => "recordDate", 'laydate' =>[], "value" => $info['recordDate']?:$this->date]),
                    must . "员工姓名：" => selectMultiple(array('table' => 'staff','value'=>$info['staffId'],'where'=>"state !='离职'", "title" => '员工', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'staffId'))
                ],
                [
                    must . "奖惩级别：" =>  radio(["name" => "level", 'value' => explode('，',para('rewardsLevel')), "checked" => $info['level']]),
                    must . "奖惩类型：" => radio(["name" => "type", 'value' => explode('，',para('rewardsType')), "checked" => $info['type']]),
                ],
                [
                    must . "奖惩事由：" => textarea(["name" => "reason", "value" => $info['reason']])
                ],
                [
                    must . "奖惩方式：" => textarea(["name" => "method", "value" => $info['method']]),
                ],
                [
                    "奖惩金额：" => text(["name" => "money", "value" => $info['money']]),
                ],
                [
                    "附件上传：" => fileUploadClass::addFileComponent($id, '奖惩记录', self::page, self::page . 'EditForm')
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 400, "html" => $html));
    }

    public function editEdit()
    {
        $fileIdArr = $this->post('fileId');
        $id = $this->post('id') ?: self::getId();
        $field = [
            'recordDate' => $this->post('recordDate'),
            'staffId' => $this->post('staffId'),
            'level' => $this->post('level'),
            'type' => $this->post('type'),
            'reason' => $this->post('reason'),
            'method' => $this->post('method'),
            'money' => $this->post('money'),
        ];
        $annotation = [
            'recordDate' => '登记日期',
            'staffId' => '员工姓名',
            'level' => '奖惩级别',
            'type' => '奖惩类型',
            'reason' => '奖惩事由',
            'method' => '奖惩方式',
        ];
        $rules = [
            'recordDate' => 'required|date',
            'staffId' => 'required',
            'level' => 'required',
            'type' => 'required',
            'reason' => 'required',
            'method' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif(!empty($field['money']) && preg_match(checkPrice,abs($field['money'])) ==0){
            $json['warn'] = '金额格式错误';
        }else {
            $field['department'] = self::findStaffDepartment($field['staffId']);
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'JCJL',
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'stid' => self::$stid,
                    'state' => '草稿',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
          if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '奖惩记录',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'auditAfter',
                            'data'=>['id'=>$info['id']]
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'cancelFun',
                            'data'=>['id'=>$info['id']]
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    /**
     * 审核通过触发方法
     * @param $data
     * @return string
     */
    public function auditAfter($data): string
    {
        return update(array('table'=>self::table,'field'=>['signStid'=>self::$stid,'deptName'=>self::findStaffDepartment(self::$stid)],'where'=>"id = '$data[id]'"));
    }

    /**
     * 撤销触发方法
     * @param $data
     * @return string
     */
    public function cancelFun($data): string
    {
        return update(array('table'=>self::table,'field'=>['signStid'=>'','deptName'=>''],'where'=>"id = '$data[id]'"));
    }
    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $button = [];
            if ($info['state'] =='草稿'){
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "edit",
                        "post" => ["id" => $info['id']],
                    ];
                }
                if ($this->power(self::page,'del')){
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }
            $button[] = [
                "name" => "上传奖惩签确",
                "type" => "弹出层",
                "cla" => $this->get('cla'),
                "fun" => "signConfirm",
                "post" => ["id" => $info['id']],
            ];
            //审核按钮
            $button = array_merge($button, $this->auditButton($info));
            $staff = query('staff',"stid = '$info[staffId]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '详细信息' => array(
                    array(
                        "登记日期" => $info['recordDate'],
                        "员工姓名" => $staff['name'],
                        "联系电话" => $staff['tel'],
                        "部门" => $info['department'],
                    ),
                    array(
                        "奖惩级别" => $info['level'],
                        "奖惩类型" => $info['type'],
                    ),
                    array(
                        "奖惩事由" => pre($info['reason']),
                    ),
                    array(
                        "奖惩方式" => pre($info['method']),
                    ),
                ),
                '附件' => array(
                    array(
                        fileUploadClass::showFile($info['id'], '奖惩记录')
                    )
                ),
                '奖惩签确' => array(
                    array(
                        fileUploadClass::showFile($info['id'], '奖惩签确')
                    )
                ),
                '系统信息' => array(
                    array(
                        "单据编号" => $info['orderNo'],
                        "签发部门" => $info['deptName'],
                        "签发人" => self::findStaff($info['signStid']),
                        "创建时间" => $info['time'],
                    ),
                    array(
                        "核算时间" => $info['passTime'],
                        "状态" => $info['state'],
                    ),
                ),
                '流程' => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id'])
                    )
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power =$word= '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word'=>$word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已复核',
            'checkTime' => $this->time
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购记录';
        } elseif ($info['state'] != '待复核') {
            $json['warn'] = '此采购记录不是待复核状态，不能确认';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待复核',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购记录';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此采购记录不是草稿状态，不能提交';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = "不是草稿状态，暂不能删除";
                } else {
                    $all = find(array('table'=>'file','where'=>"targetId = '$id'"));
                    foreach ($all['array'] as $val){
                        fileDelete($val['src']);
                        delete(array("table" =>'file', "where" => " id = '$val[id]' "));
                    }
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog","where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow","where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message","where" => " typeid = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 奖惩签确
     * @return bool|string
     */
    public function signConfirm(): bool|string
    {
        //生成表单
        $fileUpload = new fileUploadClass();
        $html = $this->layerEdit(array("table" => array(
            array(
                '附件' => $fileUpload->addFileComponent($this->post('id'), '奖惩签确', self::page, self::page . 'SignConfirmForm'),
            )
        ), 'hidden' => hidden(array('name' => 'id', 'value' => $this->post('id')))
        ));
        //返回
        return $this->layer(array("title" => "奖惩签确", "height" => 280, "width" => 900, "html" => $html,'formTwo'=>'listForm'));
    }


    /**
     * 奖惩签确
     */
    public function signConfirmEdit(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        $fileIdArr = $this->post('fileId');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有奖惩签确" . self::title . "的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $text  = '';
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info  = query(self::table, $where);
                if ($info['id']) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", (array)$fileIdArr) . "')"));
                    //添加记录
                    $text .= "{$this->control['name']}上传了" . self::title . "的奖惩签确：ID【{$id}】" . ($info['orderNo'] ? "，奖惩单号【{$info['orderNo']}】" : '') . '<br>';
                    $x++;
                }
            }

            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = "上传了{$x}条" . self::title."的奖惩签确";
            $json['warn']     = 2;
            //$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=delivery";
        }

        resp:
        return json_encode($json, 320);
    }

}

